package org.liuwei.concucrent.base07;

import java.util.concurrent.locks.StampedLock;
//读写锁的改进
//– 读不阻塞写

public class Point {
	private double x, y;
	private final StampedLock sl = new StampedLock();

	void move(double deltaX, double deltaY) { // an exclusively locked method
		long stamp = sl.writeLock();
		try {
			x += deltaX;
			y += deltaY;
		} finally {
			sl.unlockWrite(stamp);
		}
	}

	double distanceFromOrigin() { // A read-only method
		long stamp = sl.tryOptimisticRead();
		double currentX = x, currentY = y;
		if (!sl.validate(stamp)) {// 这里判断是否被改变了，如果改变了就加真正的读锁
			stamp = sl.readLock();// ，如果改变了就加真正的读锁,并且再次读取数据
			try {
				currentX = x;
				currentY = y;
			} finally {
				sl.unlockRead(stamp);
			}
		}
		return Math.sqrt(currentX * currentX + currentY * currentY);
	}

	public static void main(String[] args) {
		Point point = new Point();
		point.move(11, 11);
		System.out.println(point.distanceFromOrigin());
	}
}